package com.oreilly.ez.service.impl;

import com.oreilly.ez.entity.Payment;
import com.oreilly.ez.entity.Study;
import com.oreilly.ez.repo.PaymentRepo;
import com.oreilly.ez.service.PaymentService;
import com.oreilly.ez.util.CloneUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class PaymentServiceImpl  implements PaymentService{


    @Autowired
    private PaymentRepo paymentRepo;

    @Override
    public Payment save(Payment item) {

        // is update ??
        Integer sid = item.getSid();
        if(sid != null){
            Payment dbItem = paymentRepo.getOne(sid);

            CloneUtils.copyProperties(item, dbItem);
            CloneUtils.copyProperties(dbItem, item);

        }

        //本次交费
        BigDecimal payFee = item.getPayFee();

        Study study = item.getStudy();
        BigDecimal totalFee = study.getFee();
        study.setPayFee(totalFee.subtract(payFee));

        return paymentRepo.save(item);

    }

    @Override
    public void remove(Integer sid) {

        paymentRepo.deleteById(sid);
    }


    @Override
    public Page<Payment> find(Payment item, Pageable pageable) {

        return paymentRepo.findAll(pageable);
    }

    @Override
    public Payment findOne(Integer sid) {

        return paymentRepo.findById(sid).get();
    }


}
